package org.zk.dubbo_consumer.controller;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;


import org.zk.dubbo_consumer.util.AlipayConfigs;
import org.zk.dubbo_consumer.util.OrderUtil;
import org.zk.entity.*;
import org.zk.service.MemberService;
import org.zk.service.OrderService;
import org.zk.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.plaf.synth.SynthColorChooserUI;
import java.io.BufferedOutputStream;
import java.net.Socket;
import java.util.*;


/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author Alicelonely
 * @since 2019-12-11
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Resource
    private MemberService memberService;
    @Resource
    OrderService orderService;
    @Resource
    private UserService userService;


    /**
     * 查看VIP类型
     */



    @RequestMapping("toVip")
    public  ModelAndView get(HttpServletRequest request){
        List<Member> memberList=memberService.getAllMember();
        User user = (User) request.getSession().getAttribute("user");
        HttpSession session = request.getSession(true);
        user=userService.queryUsers(user);
        System.out.println("==================="+user.getUserVipdue());
        ModelAndView modelAndView=new ModelAndView("user/vipmenu");
        modelAndView.addObject("memberList",memberList);
        modelAndView.addObject("user",user);
        modelAndView.addObject("session",session);
        return modelAndView;
    }

    @RequestMapping("/panduan")
    @ResponseBody
    public Map panduan(HttpSession session){
        int denglu=0;
        User user = (User) session.getAttribute("user");
        Map<String,Integer> maps=new HashMap<>();
        maps.put("userId",user.getUserId());

        //判断返回值
        int num=userService.queryUser(maps);
        if(num!=0){//表示已经登录
            denglu=1;
        }
        maps.put("denglu",denglu);
        return maps;
    }


    @GetMapping("/createOrder")
    public ModelAndView createOrder(Integer memberId, Double memberMoney,HttpSession session){
        //创建一个新订单（在数据库中设置为支付订单的失效事件，失效时间为30min，失效后改为状态-1）
        Order orders=new Order();
        //订单id
        String orderId= OrderUtil.genUniqueKey();//根据工具类生成订单id
        orders.setOrderId(orderId);//订单id
        //下单人id，从session中获取当前用户
        User user= (User) session.getAttribute("user");
        user.setUserId(user.getUserId());
        orders.setUser(user);
        Member m=new Member();
        m.setMemberId(memberId);
        orders.setMember(m);
        //下单金额
        orders.setOrderTotal(memberMoney);
        //订单状态(0未支付，1已支付，-1已失效)
        orders.setOrderState(0);
        orderService.insertcreateVipOrder(orders);
        List<Member>memberList=memberService.getAllMember();
        ModelAndView modelAndView=new ModelAndView("user/vip_pay");
        modelAndView.addObject("memberList",memberList);
        modelAndView.addObject("order",orders);
        return modelAndView;
    }

    /**
     *
     * 调用支付宝接口，支付订单
     */
    @RequestMapping(value = "/goPay" ,produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String goPay(String orderId) throws Exception {
        Order order=orderService.queryVipOrder(orderId);

        //根据订单中的memberId在商品表中查询到商品的具体信息
        Member member=memberService.queryMember(order.getMember().getMemberId());
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigs.gatewayUrl, AlipayConfigs.app_id, AlipayConfigs.merchant_private_key, "json", AlipayConfigs.charset, AlipayConfigs.alipay_public_key, AlipayConfigs.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfigs.return_url);
        alipayRequest.setNotifyUrl(AlipayConfigs.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderId;
        //付款金额，必填
        Double total_amount = order.getOrderTotal();
        //订单名称（课程名），必填
        Integer subject = member.getMemberMonth();
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。
        // 取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "30m";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
    /**
     * 支付成功同步通知
     * @return
     */
    @RequestMapping(value = "/alipayVip")
    public ModelAndView alipayVip(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfigs.alipay_public_key, AlipayConfigs.charset, AlipayConfigs.sign_type);

        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            Order o=orderService.queryVipOrder(out_trade_no);
            if(o.getOrderState()==1){
                return  new ModelAndView("index");
            }
            List<Member> memberList=memberService.getAllMember();



            //=================================================================
            //1.修改订单状态，改为支付成功，已付款;
            Order orders=new Order();
            orders.setOrderId(out_trade_no);
            orders.setOrderState(1);
            orders.setOrderPayTime(new Date());
            orderService.updateOrder(orders);

            //2.修改Vip用户信息
            Order order=orderService.queryVipOrder(out_trade_no);
            System.out.println("================"+order.getUser().getUserId());
            System.out.println("================"+order.getUser().getUserVip());
            if (order.getUser().getUserVip()==0){
                userService.updateUserViptime(order.getUser().getUserId());
            }else {
                userService.updateUserxufei(order.getUser().getUserId());
            }

            System.out.println("*********************支付成功*********************");
            System.out.println("* 订单号: "+ out_trade_no);
            System.out.println("* 支付宝交易号: "+ trade_no);
            System.out.println("* 实付金额: "+total_amount);
            System.out.println("* 购买会员: "+memberList.get(0).getMemberMonth()+"年");
            System.out.println("***************************************************************");
        }else {
            System.out.println("支付, 验签失败...");
        }

        return new ModelAndView("user/success");
    }



    @RequestMapping("/success")
    public String toSuccess(HttpServletRequest request){

        return "/user/success";
    }


    public MemberService getMemberService() {
        return memberService;
    }

    public void setMemberService(MemberService memberService) {
        this.memberService = memberService;
    }

    public OrderService getOrderService() {
        return orderService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}

